<?php

class Client_Table_Privileges extends Apk_Db_Table
{
	protected $_name      = 'privileges';
    protected $_primary   = 'id';
    protected $_ERROR = '';
    protected $_lang;

    public function __construct($lang = 'ru')
    {
    	$this->_lang = $lang;
    	parent::__construct();
    }

    public function GetError()
    {
    	return $this->_ERROR;
    }


    public function GetDataList($page=1, $params=array())
    {
    	$sel = $this->getAdapter()->select()
    		  ->from($this->_name, array('id', 'title' => 'title_'.$this->_lang, 'desc' => 'desc_'.$this->_lang, 'path', 'file_name'))
    		  ->where($this->_name.'.is_active = 1')
    		  ->where($this->_name.'.is_ghost = 0')
    		  ->where($this->_name.'.is_removed = 0')
    		  ->order($this->_name.'.norder');

    	// **  Params  **
    	if(count($params) > 0)
    	foreach ($params as $k => $v)
    	switch($k)
    	{
    		case 'cats':
    			$sel->where('id_cat in (?)', $v);
    			break;
    		default:
    			$sel->where($this->_name.'.'.$k.' = ?', $v);
    	}

    	return $this->setDecorator('simpleDecorator')->getList($sel);
    }

    public function GetLast($params = null, $limit = 2)
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name, array('id', 'idt', 'title', 'desc', 'public_date', 'path', 'file_name'))
    				->where('id_cat = 415')
    				->where('is_active')
    				->where('is_removed = 0')
    				->where('is_ghost = 0')
    				->where('id_lang = ?', $this->GetLangID())
    				->order('norder')
    				->limit(3);

        	// **  Params  **
    	if(count($params) > 0)
    	foreach ($params as $k => $v)
    	switch($k)
    	{
    		case 'cats':
    			$sel->where('id_cat in (?)', $v);
    			break;
    		case 'except':
    			$sel->where('id != ?', $v);
    			break;
    		default:
    			$sel->where($this->_name.'.'.$k.' = ?', $v);
    	}

    	//echo $sel;

    	return $this->setDecorator('simpleDecorator')->getList($sel)->toArray();
    }

    public function GetTop($limit = 3)
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name, array('id', 'title', 'desc', 'public_date', 'path', 'file_name', 'idt'))
    				->join('categories', 'categories.id = articles.id_cat', array('cat_idt' => 'idt', 'cat_name' => 'menu_name_ru'))
    				->where($this->_name.'.is_active')
    				->where($this->_name.'.is_removed = 0')
    				->where($this->_name.'.is_ghost = 0')
    				->where($this->_name.'.is_top = 1')
    				->where($this->_name.'.id_lang = ?', $this->GetLangID())
    				->order($this->_name.'.norder')
    				->limit($limit);

    	return $this->setDecorator('simpleDecorator')->getList($sel)->toArray();
    }


    public function GetDataRow($id)
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name)
		    		->where($this->_name.'.is_active')
		    		->where($this->_name.'.is_removed = 0')
		    		->where($this->_name.'.is_ghost = 0');


        if(intval($id) > 0) $sel->where($this->_name.'.id = ?', $id);
		else $sel->where($this->_name.'.idt = ?', $id);

		try {
	    	$data = $this->setDecorator('simpleDecorator')->getList($sel)->getRow(0)->toArray();
		}
		catch (Exception $e)
		{
			return array();
		}

    	//$data['tags'] = $this->GetTags($id);
    	return $data;
    }


    public function GetTags($id)
    {
    	$sel = $this->getAdapter()->select()
    		  ->from('tags_to_articles')
    		  ->join('tags', 'tags.id = tags_to_articles.id_tag', array('id', 'name'))
    		  ->where('tags.is_active')
    		  ->where('tags_to_articles.id_articles = ?', $id);

    	return $this->getList($sel)->toArray();
    }

    public function GetNextBack($id = null, $params=array())
    {
    	$sel = $this->getAdapter()->select()
    		  ->from($this->_name, array('id', 'title'))
    		  ->where($this->_name.'.is_ghost = 0')
    		  ->where($this->_name.'.is_removed = 0')
    		  ->where($this->_name.'.is_active')
    		  ->where($this->_name.'.id_lang = ?', $this->GetLangID())
    		  ->order($this->_name.'.public_date desc');

    	if(!is_null($params)){
    		foreach($params as $param => $val)
    		switch ($param)
    		{
    			default:
    				$sel->where($param.' = ?', $val);
    				break;
    		}
    	}

    	$data = $this->setDecorator('simpleDecorator')->getList($sel)->toArray();

    	$ret = array();
    	$ret['count'] = count($data);
    	if($ret['count'] > 0)
    	foreach ($data as $k => $v)
    	if($v['id'] == $id)
    	{
    		$ret['pos'] = $k+1;
    		if($k != $ret['count']-1) $ret['next'] = $data[$k+1];
    		if($k != 0) $ret['back'] = $data[$k-1];
    	}

    	return $ret;
    }

    public function GetRSS()
    {
    	$today = getdate(time());
    	$today1 = mktime(0,0,0, $today['mon'], $today['mday'], $today['year']);

        $sel = $this->getAdapter()->select()
    	    ->from($this->_name, array('id', 'public_date', 'title', 'desc', 'path', 'file_name', 'body'))
    	    ->where('is_ghost = 0')
    	    ->where('is_removed = 0')
			->where('is_active')
			->where('type = 0')
			->where('public_date > ?', ($today1 - (60*60*24*7))) //sec*min*hours*days
			->where('public_date <= ?', time())
			->order('public_date desc');

		$arts = $this->getList($sel)->toArray();

		$title = Zend_Registry::get('config')->title;
        $url = Zend_Registry::get('config')->domains->front;

        $rss_generator = new Apk_RSSGenerator();
        $rss_generator->xmlWriter->startElement('rss');
        $rss_generator->xmlWriter->writeAttribute('version', '2.0');
        $rss_generator->xmlWriter->writeAttribute('xmlns:content', 'http://purl.org/rss/1.0/modules/content/');

        $rss_generator->xmlWriter->startElement('channel');
        $rss_generator->xmlWriter->writeElement('title', $title);
        $rss_generator->xmlWriter->writeElement('description', $title);
        $rss_generator->xmlWriter->writeElement('link', $url);
        $rss_generator->xmlWriter->writeElement('pubDate', date('r'));

         foreach ($arts as $item){
         	$itemTimestamp = date('r', $item['public_date']);
         	$rss_generator->xmlWriter->startElement('item');
         	$rss_generator->xmlWriter->writeElement('title', $item['title']);
         	$rss_generator->xmlWriter->writeElement('link',  $url.'/news/material/id/'.$item['id']);
         	$rss_generator->xmlWriter->writeElement('description',  $item['desc']);
         	$rss_generator->xmlWriter->writeElement('category', '');
         	$rss_generator->xmlWriter->writeElement('pubDate',  $itemTimestamp);
         	$rss_generator->xmlWriter->endElement();
         }

        $rss_generator->xmlWriter->endElement();

        $rss_generator->xmlWriter->endElement();
        $rss_generator->output();
    }

    public function AddHit($id)
    {
    	$data = $this->GetDataRow($id);

    	$d['hit_count'] = $data['hit_count'] + 1;
    	$this->update($d, 'id = '.$id);

    	return true;
    }

    public function is_rated($id, $ip_addr)
    {
    	$sel = $this->getAdapter()->select()
    		  ->from('articles_rating')
    		  ->where('ip_addr = ?', $ip_addr)
    		  ->where('id_article = ?', $id);

    	return $this->getList($sel)->count();
    }

    public function rating($data)
    {
    	if($this->is_rated($data['id_article'], $data['ip_addr'])) return false;

    	$data['date'] = time();

    	$this->getAdapter()->insert('articles_rating', $data);
    	$this->calc_rate($data['id_article']);
    	return true;
    }

    public function calc_rate($id)
    {
    	$sel = $this->getAdapter()->select()
    		  ->from('articles_rating', array('count' => 'count(id)', 'sum' => 'sum(value)'))
    		  ->where('id_article = ?', $id);

    	$data = $this->getList($sel)->getRow(0);

    	$d['rating_count'] = $data->count;
    	if($data->count > 0) $d['rating'] = $data->sum / $data->count;
    	else $d['rating'] = 0;

    	parent::update($d, 'id = '.$id);
    }

    public function comment($data)
    {
    	$data['add_date'] = time();
    	$this->getAdapter()->insert('articles_comments', $data);
    	return $this->getAdapter()->lastInsertId('articles_comments');
    }

    public function GetAccessList($a = null, $lang = 'ru')
    {
    	$ret = array();

		$sel = $this->getAdapter()->select()
					->from('access_level', array('id', 'title' => 'title_'.$lang))
					->order('title_ru');

		$data = $this->getList($sel)->toArray();

    	if(count($data) > 0 && !is_null($a))
    	foreach($data as $k => $v)
    	  	if($v['id'] == $a) $data[$k]['__attributes']['active'] = 1;

    	return $data;
    }




    //**********************************************
    // insert/update/delete

	public function insert(array $data, $user_id)
    {
    	$data['public_date'] = time();
    	$data['modify_date'] = time();
    	$data['add_date'] = time();
    	$data['add_user_id'] = $user_id;
    	$data['modify_user_id'] = $user_id;
    	$data['is_ghost'] = 0;
    	$data['is_active'] = 1;

        return parent::insert($data);
    }

    public function update(array $data, $id, $user_id = 0)
    {
    	$data['modify_date'] = time();
    	$data['modify_user_id'] = $user_id;
    	$data['is_ghost'] = 0;

    	//if(!isset($data['is_active'])) $data['is_active'] = 0;
    	//if(!isset($data['is_commented'])) $data['is_commented'] = 0;
    	//if(!isset($data['is_rated'])) $data['is_rated'] = 0;

		return parent::update($data, 'id = '.$id);
    }

    public function remove($items, $user_id)
    {
    	foreach($items as $k => $id)
    	{
	    	$data['modify_user_id'] = $user_id;
	    	$data['modify_date'] = time();
	    	$data['is_removed'] = 1;

	    	parent::update($data, 'id = '.$id);
    	}

    	return true;
	}

    public function remove_commetns($items, $aid)
    {
    	foreach($items as $k => $id)
    	{
	    	$this->getAdapter()->delete('articles_comments', 'id = '.$id);
    	}

    	$this->commetns_count($aid);

    	return true;
	}

    public function commetns_count($id)
    {
    	$sel = $this->getAdapter()->select()
    					->from('articles_comments', array('count' => 'count(id)'))
    					->where('id_article = ?', $id);
    	$count = $this->getList($sel)->getRow(0)->toArray();

    	$d['comments_count'] = $count['count'];
    	parent::update($d, 'id = '.$id);
    }


    /********************
     ***  Decorators  ***
    *********************/

    public function simpleDecorator($key, $value)
    {
        switch ($key) {
            case 'public_date':
            case 'modify_date':
            case 'add_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);
            	break;
            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }

    public function topDecorator($key, $value)
    {
        switch ($key) {
            case 'public_date':
            case 'modify_date':
            case 'add_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);
            	break;
            case 'title':
            	$result[$key] = mb_substr($value, 0, 33).'...';

            	break;
            default:
                $result[$key] = stripslashes($value);
                break;
        }
        return $result;
    }

}
?>